const initialState = {
  channelId: '0',
  articleDetail: {} as DetailType,
  articles: {} as listType,
};
type ArticleListType = {
  art_id: string;
  title: string;
  aut_id: string;
  comm_count: number;
  pubdate: string;
  aut_name: string;
  is_top: string;
  cover: {
    type: number;
  };
  images?: [];
};
type DetailType = {
  art_id: string;
  title: string;
  pubdate: string;
  aut_id: string;
  content: string;
  aut_name: string;
  aut_photo: string;
  is_followed: boolean;
  is_collected: boolean;
  attitude: number;
  comm_count: number;
  read_count: number;
  like_count: number;
};

type listType = {
  [cahnnelId: string]: {
    pre_timestamp: string;
    results: ArticleListType[];
  };
};
export type ArticleActionType =
  | { type: 'article/channelId'; payload: string }
  | {
      type: 'article/saveList';
      payload: {
        pre_timestamp: string;
        results: ArticleListType[];
        channel_id: string;
      };
    }
  | {
      type: 'article/updateList';
      payload: {
        pre_timestamp: string;
        results: ArticleListType[];
        channel_id: string;
      };
    }
  | { type: 'article/detail'; payload: DetailType };
export default function articleReducer(
  state = initialState,
  action: ArticleActionType
) {
  switch (action.type) {
    case 'article/channelId':
      return {
        ...state,
        channelId: action.payload,
      };
    case 'article/updateList':
      const { pre_timestamp, results, channel_id } = action.payload;
      const oldResults = state.articles[channel_id]?.results || [];

      return {
        ...state,
        articles: {
          ...state.articles,
          [channel_id]: {
            pre_timestamp,
            results: [...oldResults, ...results],
          },
        },
      };
    case 'article/saveList':
      const {
        pre_timestamp: time,
        results: list,
        channel_id: id,
      } = action.payload;
      return {
        ...state,
        articles: {
          ...state.articles,
          [id]: {
            pre_timestamp: time,
            results: list,
          },
        },
      };

    case 'article/detail':
      return {
        ...state,
        articleDetail: { ...action.payload },
      };
    default:
      return state;
  }
}
